package main

import (
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"net/http"
	"github.com/davyxu/ulog"
	"encoding/base64"
	//"io/ioutil"
	"os"
    "net/url"
	"time"
	"runtime"
	"strings"
)

var upGrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

func getFilePath()string{

	dir,_ := os.Getwd()
	ulog.Infoln("dir：",dir) 

	if runtime.GOOS == "windows" {
		dir = strings.Replace(dir, "\\", "/", -1)
	}

	strings.LastIndex(dir, "/")
	return dir

}

func writePicture(ws *websocket.Conn)[]byte{
	
	pic, _ := os.Open(getFilePath() + "/../../"  + "file/qd.jpg")
	defer pic.Close()

	sourcebuffer := make([]byte, 500000)
	n, _ := pic.Read(sourcebuffer)
	//base64
	sourcestring := base64.StdEncoding.EncodeToString(sourcebuffer[:n])

	return []byte(sourcestring)
}

func writeFile(ws *websocket.Conn)[]byte{

	file, _ := os.Open(getFilePath() + "/../../"  + "file/a.txt")
	defer file.Close()

	buff := make([]byte, 500000)
	n, _ := file.Read(buff)

	return buff[:n]

}

func send(c *gin.Context){

	 // create ws conn
	 u := url.URL{Scheme: "ws", Host: "localhost:8080", Path: "/echo"}
	 u.RequestURI()
	 ulog.Infof("ws url: %s", u.String())
	 ulog.Infof("connecting to %s", u.String())
  
	 ws, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
	 if err != nil {
		ulog.Errorf("dial err: %v", err)
		return
	 }
 

	defer ws.Close() 

	for {

		message := writePicture(ws)
		//message := writeFile(ws)

		if len(string(message)) <= 0 {
			break
		}

		ulog.Infof("file size: %v.", len(string(message)))


		//写入ws数据
		err = ws.WriteMessage(websocket.BinaryMessage, message)
		if err != nil {
			break
		}
		
		time.Sleep(2*time.Second)
	}

	ulog.Errorf("send fail...")

}

func main(){

	r := gin.Default()
	r.GET("/send", send)
	r.Run(":12345")

}